package controllers

import (
	"fmt"

	"gitee.com/yizhongi/wfw/util"
)

//WebhookController webhook控制器
type WebhookController struct {
	BaseController
}

// @router /webhook [get]
func (c *WebhookController) Index() {
	c.TplName = "webhook.html"
}

// @router /hookinfo [get]
func (c *WebhookController) Info() {
	Info := make(map[string]string)
	Info["ExternalIP"] = util.GetConfig(false, "externalIP", util.GetAExternalIP)
	Info["InternalIP"] = util.GetConfig(false, "internalIP", util.GetAInternalIP)
	Info["Port"] = util.GetConfig(false, "httpport", nil)
	Info["Domain"] = util.GetConfig(false, "domain", nil)
	Info["Token"] = util.GetConfig(false, "token", util.NewToken)
	Info["whAddr"] = getWebHookAddr()
	c.SuccessJson("", Info)
}

func getWebHookAddr() string {
	return fmt.Sprintf("http://%s/wh?t=%s&v=&d=", getHostInfo(), util.GetConfig(false, "token", util.NewToken))
}

// @router /savedomain [post]
func (c *WebhookController) SaveDomain() {
	var domain string
	c.Ctx.Input.Bind(&domain, "domain")
	util.SetConfig("domain", domain)
	Info := make(map[string]string)
	Info["whAddr"] = getWebHookAddr()
	c.SuccessJson("", Info)
}

// @router /newip [post]
func (c *WebhookController) NewIp() {
	Info := make(map[string]string)
	Info["ExternalIP"] = util.GetConfig(true, "externalIP", util.GetAExternalIP)
	Info["InternalIP"] = util.GetConfig(true, "internalIP", util.GetAInternalIP)
	Info["whAddr"] = getWebHookAddr()
	c.SuccessJson("", Info)
}

// @router /newtoken [post]
func (c *WebhookController) NewToken() {
	Info := make(map[string]string)
	Info["Token"] = util.GetConfig(true, "token", util.NewToken)
	Info["whAddr"] = getWebHookAddr()
	c.SuccessJson("", Info)
}

func getHostInfo() string {
	domain := util.GetConfig(false, "domain", nil)
	if domain == "" {
		domain = util.GetConfig(false, "externalIP", util.GetAExternalIP)
	}
	return fmt.Sprintf("%s:%s", domain, util.GetConfig(false, "httpport", nil))
}
